package com.atguigu.gmall.common.exception;/*
 * @author: XueYouPeng
 * @time: 23.7.11 下午 8:37
 */

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

//声明当前类就是一个全局异常处理器
@RestControllerAdvice
public class GlobalExceptionHandler {

    //处理自定义异常的
    @ExceptionHandler(value = GmallException.class)
    public Result gmallExceptionHandler(GmallException e){
        e.printStackTrace();
        return Result.build(null,e.getResultCodeEnum());
    }

    //处理其他异常的
    @ExceptionHandler(value = Exception.class)
    public Result systemExceptionHandler(Exception e){
        e.printStackTrace();
        return Result.build(null, ResultCodeEnum.SYS_ERROR);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        // 返回值表示的意思是校验不同的字段以及提示信息
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        HashMap<String, String> resultMap = new HashMap<>();
        for (FieldError fieldError : fieldErrors){
            String fieldName = fieldError.getField();
            String defaultMessage = fieldError.getDefaultMessage();
            boolean containsKey = resultMap.containsKey(fieldName);
            if (!containsKey){
                resultMap.put(fieldName , defaultMessage);
            }else {
                String message = resultMap.get(fieldName);
                message += "," + defaultMessage ;
                resultMap.put(fieldName , message);
            }
        }

        Result result = new Result();
        result.setCode(9002);
        result.setMessage(JSON.toJSONString(resultMap));
        return result;
    }

}
